<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>formData上传 + 上传进度</title>
    <style>
        #progress{
            display: none;
        }
        .outer{
            background-color: darkgray;
            height: 12px;
            width: 300px;
            float: left;
        }
        .inner{
            background-color: green;
            height: 12px;
            width: 0;
        }
        .rate{
            font-size: 12px;
            float: left;
        }
    </style>
</head>
<body>
    <h1>formData上传 + 上传进度</h1>
    <input id="file" type="file" value="请选择文件" onchange="fileChange();">
    <input type="button" value="上传" onclick="upload();">
    <div id="progress">
        <div class="outer">
            <div class="inner"></div>
        </div>
        <span class="rate"></span>
    </div>
    <script src="jquery.min.js"></script>
    <script>
        $(function(){
            //alert(1);
        })

        function fileChange(){
            $("#progress").hide();
            $(".inner").css("width", 0);
        }

        function upload(){

            //debugger;
            var myFile = $("#file")[0].files[0];
            var formData = new FormData();
            formData.append("file", myFile);
            $.ajax({
                type: "POST",
                url: '/formDataProgress/upload',
                data: formData,
                contentType: false, //必须
                processData: false, //必须
                //dataType: "json",
                xhr: function(){

                    $("#progress").show();

                    let xhr = new XMLHttpRequest();

                    xhr.upload.addEventListener('progress', function (e) {
                        let loaded = e.loaded;
                        let total = e.total;
                        var rate = (loaded/total) * 100;
                        console.log(e, '上传', rate + '%');
                        $(".inner").css("width", loaded / total * 300 + "px" );
                        $(".rate").html(Math.floor(rate) + '%');
                    })

                    return xhr;
                },
                success: function(res){

                    console.log("success");
                    console.log(res);
                    alert("上传完成")
                    //清空上传文件的值
                    $('#file').val('');
                    $("#progress").html("");
                    //$('#success_image').attr('src', res.realPathList[0]);
                },
                error : function(res) {
                    console.log("error");
                    console.log(res);
                    //清空上传文件的值
                    //$('#btn1').val('');
                }
            })
        }
    </script>
</body>
</html>